import { returnUrlToLinea } from "_commonFn/url.js"
import { getCookie } from "_commonFn/cookie.js"
import { api } from "api/apiPath.js"

// Manages whether the request is repeated
class RequestManager {
    constructor() {
        this.getApiFlag = {}
    }

    // 根据生成的flag值是否为getApiFlag的属性来判断是否与正在请求的请求相同,否则返回flag值
    isRequesting(url, type, contentType, taskId) {
        
        const flag = taskId || url + type + contentType // 请求的唯一标志
        // console.log('flag', flag)
        // console.log('taskId', taskId)

        if (this.getApiFlag[flag]) return false // 属于重复执行，忽略此次请求

        this.addFlag(flag) // 添加标志

        return flag
    }

    // 添加标志,标志作为属性 值默认为1
    addFlag(flag, value = 1) {
        this.getApiFlag[flag] = value
    }

    // 删除属性
    deleteFlag(flag) {
        if (this.getApiFlag[flag]) delete this.getApiFlag[flag]
    }
}

const requestManagerObj = new RequestManager()

class RequestApiManager{
    constructor({
        data = '',
        url = '', 
        type = 'get', 
        contentType = 'application/x-www-form-urlencoded', 
        timeout = 10000,
        taskId = '', 
        version = "V1",
        dataType = 'json',
        timeoutFn = '',
        requestHeader = {}
    }){
        this.data = data
        this.url = url
        this.type = type
        this.contentType = contentType
        this.timeout = timeout
        this.taskId = taskId
        this.version = version
        this.dataType = dataType
        this.timeoutFn = timeoutFn
        this.requestHeader = requestHeader
    }

    // 开始执行
    start(){
        const that = this
        const flag = requestManagerObj.isRequesting(that.url, that.type, that.contentType, that.taskId) // 创建请求标志
        return new Promise((resolve, reject) => {
            if (!flag || !that.url) {
                setTimeout(() => {
                    reject({ errcode: 2000 }, 2000)
                }, 1)
            }else{
                that.xhr = that.createXMLHttpRequest() // 创建XHR
                that.xhr.onreadystatechange = () => { // 开始监听
                    if(that.xhr.readyState == 4){
                        requestManagerObj.deleteFlag(flag) // 删除请求标志
                        if(that.xhr.status == 200){ // 请求成功
                            let responseText = that.xhr.responseText
                            if(that.dataType === 'json') {
                                responseText = JSON.parse(responseText)
                                if(responseText.errcode == 1100){
                                    // console.log('1100 requestUrl', that.url)
                                    const urlN = window.location.href
                                    if (!urlN.includes('LoginChose.html') && !urlN.includes('index.html') && urlN.includes('.html')) { // 如果不是首页
                                        const html = '?u=' + encodeURIComponent(returnUrlToLinea())
                                        window.location.href = 'LoginChose.html' + html
                                    } else {
                                        resolve(responseText)
                                    }
                                } else if(responseText.errcode == 500){
                                    window.location.href = 'under-maintenance.html'
                                }else{
                                    resolve(responseText, 'success')
                                }
                            }
                        }else{
                            reject(that.xhr.responseText)
                        }
                    }
                }
                that.open() // 初始化请求
                that.setRequestHeader() // 设置请求头
                that.send() // 发送 HTTP 请求
            }
        })
    }

    // 初始化请求
    open(){
        const that = this
        if(typeof that.data === 'object' && that.contentType === 'application/x-www-form-urlencoded' && (that.type === 'get' || that.type === 'GET')){
            that.url += '?' + that.objToStr(that.data)
            that.data = ''
        }else if(typeof that.data === 'object' && that.contentType === 'application/x-www-form-urlencoded' && (that.type === 'post' || that.type === 'POST')){
            that.data = that.objToStr(that.data, 'post')
        }
        that.xhr.open(that.type, that.url, true)
        that.xhr.timeout = that.timeout // 设置超时时间
        that.xhr.ontimeout = that.timeoutFn // 请求超时后执行的函数
    }

    // 设置请求头
    setRequestHeader(){
        const that = this
        if(that.contentType === 'application/x-www-form-urlencoded' && (that.type === 'post' || that.type === 'POST')){
            that.xhr.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01')
        }
        that.xhr.setRequestHeader('Content-Type', that.contentType)
        that.xhr.setRequestHeader('Version', that.version)
        that.xhr.setRequestHeader("Ticket", getCookie('Ticket'))
        const requestHeaderKeyArr = Object.keys(that.requestHeader)
        if(requestHeaderKeyArr.length > 0){
            requestHeaderKeyArr.forEach(key => {
                that.xhr.setRequestHeader(key, that.requestHeader[key])
            })
        }
    }

    // 发送 HTTP 请求
    send(){
        const that = this
        that.xhr.send(that.data)
    }

    // 创建XHR
    createXMLHttpRequest(){
        let xhr
        try {
            xhr = new XMLHttpRequest()
        } catch (e) {
            console.error(e)
        }
        return xhr
    }

    // 遍历对象属性拼接成Url参数格式的字符串
    objToStr(obj){
        let str = ''
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                if(str){
                    str += `&${key}=${obj[key]}`
                }else{
                    str = `${key}=${obj[key]}`
                }
            }
        }
        return str
    }
}

function requestApi({
    data = "",
    url = "",
    type = "get",
    contentType = "application/x-www-form-urlencoded",
    timeout = 10000,
    taskId = "",
    version = "V1",
    dataType = "json",
    timeoutFn = "",
    requestHeader = {}
}){
    return new RequestApiManager({ data, url, type, contentType, timeout, taskId, version, dataType, timeoutFn, requestHeader }).start()
}

// 获取网站基本配置参数接口
function getWebsiteConfig({parmsStr = '', fn = '', explain = ''}){
    if(typeof fn === 'function'){
        requestApi({
            url: `${api}/GetWebConfig/${parmsStr}`
        })
        .then(res => {
            console.log(`${explain} res`, res)
            if (res.errcode == 1000) {
                fn(res.data)
            } else {
                showError(res.message)
                fn('')
            }
        }, res => {
            console.log('fail res', res)
            if(res.errcode != 2000){
                showError('服务器正在修整')
            }
            fn('')
        })
        .catch(res => {
            console.log('catch res', res)
            showError('服务器正在修整，请稍后')
            fn('')
        })
    }
}

export { requestApi, getWebsiteConfig }